<template>
  <div>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>修改密码</span>
      </div>
      <div>
        <el-form
          :model="ruleFormData"
          :rules="rules"
          ref="ruleForm"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="原密码" prop="oldPwd">
            <el-input v-model="ruleFormData.oldPwd"></el-input>
          </el-form-item>
          <el-form-item label="新密码" prop="newPwd">
            <el-input v-model="ruleFormData.newPwd" type="password"></el-input>
          </el-form-item>
          <el-form-item label="确认新密码" prop="reNewPwd">
            <el-input v-model="ruleFormData.reNewPwd" type="password"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm('ruleForm')">立即修改</el-button>
            <el-button @click="resetForm('ruleForm')">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
  </div>
</template>

<script>
import { resetPwd } from '@/api/user'
export default {
  data() {
    // 定义一个密码校验是否相同的方法
    const validatorPwd = (rule, value, callBack) => {
      if (value != this.ruleFormData.newPwd) {
        callBack(new Error("两次输入密码不一致"));
      } else {
        callBack();
      }
    };
    return {
      ruleFormData: {
        oldPwd: "",
        newPwd: "",
        reNewPwd: ""
      },
      rules: {
        oldPwd: [
          { required: true, message: "请输入原密码", trigger: "blur" },
          { min: 4, max: 8, message: "长度在 4 到 8 个字符", trigger: "blur" }
        ],
        newPwd: [
          { required: true, message: "请输入新密码", trigger: "blur" },
          { min: 4, max: 8, message: "长度在 4 到 8 个字符", trigger: "blur" }
        ],
        reNewPwd: [
          { required: true, message: "请确认新密码", trigger: "blur" },
          { min: 4, max: 8, message: "长度在 4 到 8 个字符", trigger: "blur" },
          { validator: validatorPwd, trigger: "blur" }
        ]
      }
    };
  },
  methods:{
    submitForm(ruleFormData) {
        this.$refs[ruleFormData].validate(async (valid) => {
          if (valid) {
            const userInfo =JSON.parse(localStorage.getItem('userInfo'))
            const data = {'id':userInfo.id,'oldPwd':this.ruleFormData.oldPwd,"newPwd":this.ruleFormData.newPwd}
            await resetPwd(data).then(res=>{
              if(res.data.code == 200){
                this.$router.push('/login')
              }
            })
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
    resetForm(ruleFormData) {
      this.$refs[ruleFormData].resetFields();
    }
  }
};
</script>